package com.sicent.upms.operate.data;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.sicent.operate.common.base.dao.PageInfo;
import com.sicent.operate.common.util.CookieUtils;
import com.sicent.operate.common.util.FormatUtils;
import com.sicent.operate.common.util.Md5Utils;
import com.sicent.operate.common.util.RedisUtils;
import com.sicent.upms.operate.dto.ResourceDto;
import com.sicent.upms.operate.model.ManagerResource;
import com.sicent.upms.operate.model.ManagerRole;
import com.sicent.upms.operate.model.ManagerUserInfo;
import com.sicent.upms.operate.service.ManagerUserInfoService;

@Component
public class UserData {

	Logger logger=LoggerFactory.getLogger(UserData.class);
	
	@Autowired
	private ManagerUserInfoService managerUserInfoService;
	
	public PageInfo<ManagerUserInfo> findByPage(PageInfo<ManagerUserInfo> page){
		return managerUserInfoService.getByPage(page);
	}
	
	public void addUser(ManagerUserInfo managerUserInfo){
		ManagerUserInfo old=managerUserInfoService.getByUserName(managerUserInfo.getUserName());
		if(old!=null){
			throw new RuntimeException("用户已存在【"+managerUserInfo.getUserName()+"】");
		}
		String passWord=managerUserInfo.getUserPassword();
		passWord=Md5Utils.MD5Str32(Md5Utils.MD5Str32(passWord));
		managerUserInfo.setUserPassword(passWord);
		try {
			managerUserInfo.setCreateTime(FormatUtils.getDateSecond(new Date()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		managerUserInfoService.save(managerUserInfo);
	}
	
	public void userLogin(String userName,String userPassword,
			HttpServletRequest request,HttpServletResponse response){
		ManagerUserInfo user=managerUserInfoService.getByUserName(userName);
		if(user==null){
			throw new RuntimeException("用户不存在");
		}
		String password=Md5Utils.MD5Str32(Md5Utils.MD5Str32(userPassword));
		if(!user.getUserPassword().equals(password)){
			throw new RuntimeException("用户或密码错误");
		}
		if(user.getUserStatus().equals(ManagerUserInfo.USER_STATUS_NO)){
			throw new RuntimeException("用户被禁用");
		}
		//通过用户名和密码MD5加密获得签名
		String signature=Md5Utils.MD5Str32(userName+"`:@aq"+password+"008");
		
		CookieUtils.setCookie(response, CookieUtils.LONG_COOKIE, signature);
		//等权限系统加载好以后 就做权限缓存 现在暂时缓存username
		RedisUtils.setAndExpire(signature, userName, 30*60);
		// 登录成功 写入记录登录信息
	}
	
	public List<ResourceDto> getAllResource(){
		ManagerResource queryInfo=new ManagerResource();
		queryInfo.setStatus(ManagerResource.STATUS_YES);
		List<ManagerResource> list=managerUserInfoService.getAllResource(queryInfo);
		//查找出所有一级目录 二级目录
		List<ManagerResource> listFirst=new ArrayList<ManagerResource>();
		List<ManagerResource> listSecond=new ArrayList<ManagerResource>();
        for (ManagerResource managerResource : list) {
			if(managerResource.getResourceType().equals(ManagerResource.TYPE_FIRST)){
				listFirst.add(managerResource);
			}else{
				listSecond.add(managerResource);
			}
		}
        list=null;
        //一二级目录 归类
        List<ResourceDto> listDto=new ArrayList<ResourceDto>();
        for (ManagerResource managerResource : listFirst) {
        	ResourceDto resourceDto=new ResourceDto();
        	List<ManagerResource> seconds=new ArrayList<ManagerResource>();
        	for (ManagerResource second : listSecond) {
				if(managerResource.getResourceId().equals(second.getParentId())){
					seconds.add(second);
				}
			}
        	resourceDto.setFirst(managerResource);
        	resourceDto.setSeconds(seconds);
        	listDto.add(resourceDto);
		}
		return listDto;
	}
	
	public void addResource(ManagerResource resource){
		try {
			if(0==resource.getParentId()){
				resource.setParentId(null);
				resource.setResourceType(ManagerResource.TYPE_FIRST);
			}else{
				resource.setResourceType(ManagerResource.TYPE_SECOND);
			}
			resource.setCreateTime(FormatUtils.getDateSecond(new Date()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		resource.setStatus(ManagerResource.STATUS_YES);
		managerUserInfoService.addResource(resource);
	}
	
	public PageInfo<ManagerRole> getAllRole(PageInfo<ManagerRole> pageInfo){
		return managerUserInfoService.getAllRole(pageInfo);
	}
	
	public void addRole(ManagerRole role){
		try {
			role.setCreateTime(FormatUtils.getDateSecond(new Date()));
			managerUserInfoService.addRole(role);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void addRoleResource(Integer roleId,String roles){
		//获得返回的菜单编号啦
		List<String> list=JSONArray.parseArray(roles, String.class);
		Map<Integer, List<Integer>> mapResource=new HashMap<Integer, List<Integer>>();
		for (String string : list) {
			String[] res=string.split("-");
			List<Integer> childs=mapResource.get(Integer.valueOf(res[0].trim()));
			if(childs==null){
				childs=new ArrayList<Integer>();
				childs.add(Integer.valueOf(res[1].trim()));
				mapResource.put(Integer.valueOf(res[0].trim()), childs);
			}else{
				childs.add(Integer.valueOf(res[1].trim()));
				mapResource.put(Integer.valueOf(res[0].trim()), childs);
			}
		}
		//该执行添加任务了
		logger.info(" role resource "+JSONArray.toJSONString(mapResource));
		managerUserInfoService.addRoleResource(mapResource,roleId);
	}
	
	public List<ManagerRole> getAllUseRole(){
		ManagerRole managerRole=new ManagerRole();
		managerRole.setStatus(ManagerRole.STATUS_USED);
		return managerUserInfoService.getAllRole(managerRole);
	}
	
}
